﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;

namespace LowLevelGraphics.Filter
{
    /// <summary>
    /// Special "Darkness" Filte. Decide yourself if it makes any sense.
    /// The darkness is reached by subtracting each color itself multiplied
    /// with a factor amount. If this value gets bigger than 255
    /// it's corrected by a modulo 255 operator.
    /// </summary>
    public class Darkness : BaseImageFilter
    {
        protected int m_nAmount = 10;

        /// <summary>
        /// Default constructor
        /// </summary>
        public Darkness()
            : this(10)
        {
        }

        /// <summary>
        /// primary constructor
        /// </summary>
        /// <param name="_nAmount"></param>
        public Darkness(int _nAmount)
        {
            m_nAmount = _nAmount;
        }

        /// <summary>
        /// used by clone to create a deep copy
        /// </summary>
        /// <param name="_darkness"></param>
        internal Darkness(Darkness _darkness)
        {
            this.m_nAmount = _darkness.m_nAmount;
        }

        /// <summary>
        /// Gets or sets the intensity
        /// </summary>
        public int Intensity
        {
            get { return m_nAmount; }
            set { m_nAmount = value; }
        }

        /// <summary>
        /// Executes this filter
        /// </summary>
        /// <param name="_bitmap"></param>
        /// <returns></returns>
        public override UnsafeBitmap Execute(UnsafeBitmap _bitmap)
        {
            int p = 0;
            UnsafeBitmap bitmap = _bitmap;

            int nHeight = bitmap.Height;
            int nWidth = bitmap.Width;

            int y = 0;
            int x = 0;

            Color color = Color.Transparent;
            for (y = 0; y < nHeight; y++)
            {
                for (x = 0; x < nWidth; x++)
                {
                    color = bitmap.GetPixel(x,y);
                    bitmap.SetPixel(x, y, Color.FromArgb(
                        Math.Max(color.R - ((color.R * m_nAmount) % 255),0),
                        Math.Max(color.G - ((color.G * m_nAmount) % 255),0),
                        Math.Max(color.B - ((color.B * m_nAmount) % 255),0)
                        ));
                }
            }
            return _bitmap;
        }

        /// <summary>
        /// used to create a deep copy
        /// </summary>
        /// <returns></returns>
        public override object Clone()
        {
            return new Darkness(this);
        }
    }
}
